package com.dwyinyuan.producer;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.concurrent.BlockingQueue;

public class MeinvlaProducer implements Runnable {

    private String name;
    private BlockingQueue<String> blockingQueue;

    public MeinvlaProducer(String name, BlockingQueue<String> blockingQueue) {
        this.name = name;
        this.blockingQueue = blockingQueue;
    }

    @Override
    public void run() {
        Document doc = null;
        try {
            for (int i = 1; i < 2; i++) {
                System.out.println("current page:" + i);
                System.out.println("-----------------------------------");
                //获取3分类下的列表
                doc = Jsoup.connect("http://www.meinvla.net/list/3-" + i + ".html").get();

                Elements sections = doc.getElementsByClass("effect5");
                for (Element ele : sections) {
                    String href = ele.attr("href");
                    //进入详情下载图片
                    doc = Jsoup.connect("http://www.meinvla.net" + href).get();
                    Elements body = doc.getElementsByAttributeValue("data-fancybox", "gallery");
                    for (Element element : body) {
                        String url = element.attr("href").replace("//", "http://");
                        blockingQueue.put(url);
                        System.out.println(name + " put： " + url);
                    }
                }
            }
            //消费者根据""退出while循环
            blockingQueue.put("");
            System.out.println("-----------------------------------");
            System.out.println(name + " is over");
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}
